"use strict";

import Vue from 'vue';
import qs from "qs";
import axios from "axios";

const baseHost = 'http://front.cd2c19dacf66e4107927b899d29ced135.cn-beijing.alicontainer.com';
const endHost = 'http://end.cd2c19dacf66e4107927b899d29ced135.cn-beijing.alicontainer.com';

// 获得 query 参数
let getParameterByName = function (name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[[\]]/g, '\\$&');
    var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, ' '));
};

let setCookie = (name,value,days) => {
    let expires = "";
    if (days) {
        let date = new Date();
        date.setTime(date.getTime() + (days*24*60*60*1000));
        expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + (value || "")  + expires + "; path=/";
};
let getCookie = (name) => {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)===' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
};

// 推广ID
let promotionID = function(){
    let pid = getParameterByName("pid"); // 从 query 参数中获取
    if(pid) {
        setCookie("promotion_id", pid, 30) // 设置到 cookie 中
    } else {
        pid = getCookie("promotion_id"); // 从 cookie 中获取
    }
    if(pid) {
        return pid
    } else {
        return ""
    }
}();

// Full config:  https://github.com/axios/axios#request-config
// axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || '';
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

let config = {
    baseURL: baseHost,
    endHost: endHost,
    promotionID: promotionID,
    getQuery(name) {
      return getParameterByName(name)
    },
    timeout: 15 * 1000,
    withCredentials: false, // Check cross-site Access-Control
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
    }
};

// 请求预处理
let requestParser = (config) => {
    let method = config.method.toUpperCase();
    if (method === "POST" || method==="PUT") {
        config.data = qs.stringify(config.data,{arrayFormat: 'brackets'});
    }
    if(config.params && config.params.unset) {
        config.params = null;
    } else {
        config.params = {
            promotion_id: promotionID?promotionID:"",
            ...config.params // 保留原来的参数
        };
    }
    return config;
};
const _axios = axios.create(config);

_axios.interceptors.request.use(requestParser,  (error) => {
    return Promise.reject(error);
});

Plugin.install = function(Vue, options) {
  Vue.axios = _axios;
  window.axios = _axios;
  Object.defineProperties(Vue.prototype, {
    axios: {
      get() {
        return _axios;
      }
    },
    $axios: {
      get() {
        return _axios;
      }
    },
  });
};
Vue.use(Plugin);

export default Plugin;
